#!/bin/bash

function usage() {
  echo usage : jfdeb outputfile-version-release.deb arch [deb-control-folder [files-list]]
  echo - arch : any, x32, x64, a32, a64
  echo - deb-control-folder : holds deb control files \(default = deb\)
  echo - files-list : lists data files \(one per line\) \(default = files.lst\)
  exit
}

function error() {
  echo Error : $1
  exit
}

if [ "$1" = "" ]; then usage; fi
if [ "$2" = "" ]; then usage; fi
if [ "$1" = "--help" ]; then usage; fi
if [ "$1" = "-h" ]; then usage; fi

CONTROL_FILES=deb
DEB=$1
FILES=files.lst
if [ -f files-debian.lst ]; then FILES=files-debian.lst; fi
if [ ! "$3" = "" ]; then CONTROL_FILES=$3; fi
if [ ! "$4" = "" ]; then FILES=$4; fi

ARCH=$2
BITS=${ARCH:1:2}
if [ -f files-$BITS.lst ]; then FILES=files-$BITS.lst; fi

java -cp /usr/share/java/javaforce.jar javaforce.utils.GenPkgInfo debian $ARCH $FILES

TMPDIR=jfdeb.$RANDOM

#build control.tar.gz (gz only)
if [ -f control.tar.gz ]; then rm -f control.tar.gz; fi
mkdir $TMPDIR
cp $CONTROL_FILES/* $TMPDIR
cd $TMPDIR
tar czf ../control.tar.gz *
cd ..
rm $TMPDIR/*
rmdir $TMPDIR

#build data.tar.bz2 (gz,bz2,lzma,others?)
if [ -f data.tar.bz2 ]; then rm -f data.tar.bz2; fi
tar cjf data.tar.bz2 -T $FILES

#build $DEB
echo 2.0 > debian-binary
rm -f $DEB 2>/dev/null
#NOTE:debian-binary MUST be 1st file listed
ar mc $DEB debian-binary control.tar.gz data.tar.bz2

rm -f debian-binary 2>/dev/null
rm -f control.tar.gz 2>/dev/null
rm -f data.tar.bz2 2>/dev/null

echo Complete!
